'''
Created on Nov 2, 2009

@author: matthewlepage
'''

class Grid():
    ''' The world grid representation
    '''
    
    def __init__(self, size, seen):
        self.size = size
        self.objects = []
        self.gridrepr = []
        for i in range (0, size):
            list = []
            for j in range (0, size):
                list.append(GridElement((i,j), seen))
            self.gridrepr.append(list)
        
    # Adds an object to the gui and grid
    def addObj(self, object):
        self.objects.append(object)
        (y, x) = object.loc
        self.gridrepr[y][x].contents.append(object)
 
    # Checks to see if a given location has an object in it
    def checkLoc(self, location):
        for obj in self.objects:
            if obj.location == location:
                return obj
        return None

    # Returns the object at a given Location
    def getLoc(self, object):
        for obj in self.objects:
            if obj == object.location:
                return obj
        return None ## throw error?
    
    # Removes an object to the gui and grid
    def remove(self, object):
        self.objects.remove(object)
        (y, x) = object.rowcol
        self.gridrepr[y][x].remove(object)

    
    # Returns a list of all objects within range of a location
    def checkRadius(self, location, range):
        objs = []
        for i in range(1, range+1):
            for j in range(1, range+1-i):
                for (a,b) in ((1,1 ),(1,-1 ),(-1,-1 ),(-1,1 )):
                    content = self.checkLoc((a*i,b*j))
                    objs.extend(content)

class GridElement:
    ''' Representation for each square in the grid.
    Contains the square's coordinates, its contents,
    and whether it has been seen or not.
    '''
    def __init__(self, rowcol, seen):
        self.loc = rowcol
        self.contents = []
        self.viewed = seen
    
    def __repr__(self):
        return str(self.contents)
    
    def contains(self, type):
        for obj in self.contents:
            if isinstance(obj, type):
                return True
        return False
